package com.gzx.asr.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DownloadFileUtil {

    private DownloadFileUtil() {
    }

    //
    public static void main(String[] args) {
        try {
            //解析csv文件,导出时候不要包含列的标题
            String csvFilePath = "C:\\Users\\Baolo\\Desktop\\202505录音.csv"; // 替换为你的CSV文件路径
            List<String> firstColumnData = readFirstColumn(csvFilePath);
            log.info("csv数量 {} ", firstColumnData.size());
            for (String url : firstColumnData) {
                if (ObjectUtils.isEmpty(url)) {
                    continue;
                }
                downloadFile(url);
                log.info("{} 处理成功 ", url);
            }
            log.info("下载完成");
        } catch (Exception e) {
            log.error("下载错误 ", e);
        }
    }

    //读取本地csv文件
    public static List<String> readFirstColumn(String filePath) {
        List<String> firstColumn = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分割每一行的数据
                String[] values = line.split(",");
                if (values.length > 0) {
                    // 添加第一列数据到列表中
                    firstColumn.add(values[0]);
                }
            }
        } catch (IOException e) {
            log.error("读取文件出错", e);
        }

        return firstColumn;
    }

    //下载oss文件到本地
    public static String downloadFile(String fileUrl) {
        // 根据操作系统设置基础路径（确保末尾带分隔符）
        String basePath;
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            basePath = "D:\\asr\\download\\";
        } else {
            basePath = "/root/asr/download/";
        }

        // 创建下载目录（如果不存在）
        File downloadDir = new File(basePath);
        if (!downloadDir.exists() && !downloadDir.mkdirs()) {
            throw new RuntimeException("无法创建目录: " + basePath);
        }

        // 从URL提取文件名并解码特殊字符
        String fileName = extractFileName(fileUrl);

        // 拼接完整文件路径
        return getLocalFilePath(fileUrl, basePath, fileName);
    }

    private static String getLocalFilePath(String fileUrl, String basePath, String fileName) {
        String localFilePath = basePath + fileName;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            fileUrl = fileUrl.trim(); // 去除前后空格
            if (fileUrl.startsWith("\uFEFF")) {
                fileUrl = fileUrl.substring(1); // 去除BOM头
            }
            fileUrl = fileUrl.replaceAll("\"", "");

            URL url = new URI(fileUrl).toURL();
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            inputStream = connection.getInputStream();
            outputStream = new FileOutputStream(localFilePath);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error("下载文件出错", e);
        } finally {
            //释放流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception ex) {
                log.error("释放流出错", ex);
            }
        }
        return localFilePath;
    }

    // 提取并解码文件名组件
    private static String extractFileName(String fileUrl) {
        // 获取原始文件名
        String rawName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);

        // 处理URL编码和查询参数
        String decodedName = URLDecoder.decode(rawName, StandardCharsets.UTF_8);

        // 过滤非法字符（Windows）
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            decodedName = decodedName.replaceAll("[\\\\/:*?\"<>|]", "");
        }
        return decodedName;
    }
}
